<template>
  <div id="app">
    <div class="paper-contain">
      <div class="paper-order">
        <el-card class="box-card">
          <div class="text item">这里是试卷名称</div>
          <div class="paper-message">
            <span>总分: 100</span><br>
            <span>时长: 100分钟</span>
          </div>
          <el-divider></el-divider>
          <div class="text item">
            <span>题型:</span>
            <div class="paper-question-type">
              <span v-for="(item,index) in questionType"
                    :key="index"
                    @click="changeQuestionType(index)"
                    :class="{checkedType:index === questionTypeNum}">{{ item }}
              </span>
            </div>
          </div>
          <el-divider></el-divider>
          <div class="text item">
            <div class="paper-question-num">
              <div v-show="this.questionTypeNum===0&&this.isOrderShow">
                <span
                  v-for="(item,index) in singleChoice"
                  :key="item.qid"
                  @click="changeQuestionNum(index)"
                  :class="{checkedNum:index === questionNum}">{{ item.order }}
                </span>
              </div>
              <div v-show="this.questionTypeNum===1&&this.isOrderShow">
                <span
                  v-for="(item,index) in multipleChoice"
                  :key="item.qid"
                  @click="changeQuestionNum(index)"
                  :class="{checkedNum:index === questionNum}">{{ item.order }}
                </span>
              </div>
              <div v-show="this.questionTypeNum===2&&this.isOrderShow">
                <span
                  v-for="(item,index) in judgment"
                  :key="item.qid"
                  @click="changeQuestionNum(index)"
                  :class="{checkedNum:index === questionNum}">{{ item.order }}
                </span>
              </div>
              <div v-show="this.questionTypeNum===3&&this.isOrderShow">
                <span
                  v-for="(item,index) in fillTheBlanks"
                  :key="item.qid"
                  @click="changeQuestionNum(index)"
                  :class="{checkedNum:index === questionNum}">{{ item.order }}
                </span>
              </div>
              <div v-show="this.questionTypeNum===4&&this.isOrderShow">
                <span
                  v-for="(item,index) in shortAnswer"
                  :key="item.qid"
                  @click="changeQuestionNum(index)"
                  :class="{checkedNum:index === questionNum}">{{ item.order }}
                </span>
              </div>
            </div>
          </div>
          <el-divider></el-divider>
          <div class="paper-remaining-time">
            <span>剩余时间:{{ h }}时{{ m }}分{{ s }}秒</span>
          </div>
          <el-divider></el-divider>
          <div class="paper-submit">
            <el-button type="primary" @click="finishPaper">提交试卷</el-button>
            <el-button @click="submitPaper">取 消</el-button>
          </div>
        </el-card>
      </div>
      <div class="paper-question-content t">
        <div v-show="this.questionTypeNum===0 && this.isQuestionShow">
          <div class="paper-stem">{{this.order}}、
            <span v-html="this.stem"></span>
          </div>
          <el-divider></el-divider>
          <div class="paper-options">
            <el-radio-group v-model="singleChoiceRadio" @change="changeSingleOptions">
              <el-radio>
                A、<span v-html="this.options[0]"></span>
              </el-radio>
              <br>
              <el-radio>
                B、<span v-html="this.options[1]"></span>
              </el-radio>
              <br>
              <el-radio>
                C、<span v-html="this.options[2]"></span>
              </el-radio>
              <br>
              <el-radio>
                D、<span v-html="this.options[3]"></span>
              </el-radio>
              <br>
            </el-radio-group>
          </div>
        </div>
        <div v-show="this.questionTypeNum===1 && this.isQuestionShow">
          <div class="paper-stem">
            {{ this.order }}、<span v-html="this.stem"></span>
          </div>
          <el-divider></el-divider>
          <div class="paper-options">
            <el-checkbox-group v-model="multipleChoiceRadio" @change="changeMultiOptions">
              <el-checkbox label="A">A、<span v-html="this.options[0]"></span></el-checkbox>
              <el-checkbox label="B">B、<span v-html="this.options[1]"></span></el-checkbox>
              <el-checkbox label="C">C、<span v-html="this.options[2]"></span></el-checkbox>
              <el-checkbox label="D">D、<span v-html="this.options[3]"></span></el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div v-show="this.questionTypeNum===2 && this.isQuestionShow">
          <div class="paper-stem">
            {{ this.order }}、<span v-html="this.stem"></span>
          </div>
          <el-divider></el-divider>
          <div class="paper-options">
            <el-radio-group v-model="judgmentRadio" @change="changeJudgeOptions">
              <el-radio label="0">正确</el-radio>
              <br>
              <el-radio label="1">错误</el-radio>
              <br>
            </el-radio-group>
          </div>
        </div>
        <div v-show="this.questionTypeNum===3 && this.isQuestionShow">
          <div class="paper-stem">
            {{ this.order }}、<span v-html="this.stem"></span>
          </div>
          <el-divider></el-divider>
          <div class="paper-fill">
            <el-tooltip class="item" effect="light" content="请用空格隔开答案" placement="top">
              <el-input v-model="fillTheBlanksAnswer" placeholder="请输入答案"></el-input>
            </el-tooltip>
            <el-button type="primary" @click="preserve">保存</el-button>
          </div>
        </div>
        <div v-show="this.questionTypeNum===4 && this.isQuestionShow">
          <div class="paper-stem">
            {{ this.order }}、<span v-html="this.stem"></span>
          </div>
          <el-divider></el-divider>
          <div class="paper-short">
            <el-input v-model="shortAnswerAnswers" placeholder="请输入答案"></el-input>
            <el-button type="primary" @click="preserve">保存</el-button>
          </div>
        </div>
      </div>
      <div class="paper-face">
        <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>
        <canvas style="display:none;" id="canvasCamera" :width="videoWidth" :height="videoHeight"></canvas>
      </div>
    </div>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <span>考试过程中请不要切屏或退出后台喔！</span>
      <span>下一次将直接提交试卷！</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import {addFaceToTeacher, endExam, randImage, returnOriginalState, startExam} from "../../api/data";
import {Loading} from 'element-ui';

export default {
  name: "index",
  data() {
    return {
      dialogVisible: false,
      dialogCount: 0,//切屏次数
      result: {
        examPaperCode: '',
        examId: 0,
        singleChoice: [
          {
            qid: 0,
            answer: ''
          }
        ],
        multipleChoice: [
          {
            qid: 0,
            answers: []
          }
        ],
        judgment: [
          {
            qid: 0,
            answer: 0
          }
        ],
        fillTheBlanks: [
          {
            qid: 0,
            answers: ''
          }
        ],
        shortAnswer: [
          {
            qid: 0,
            answer: ''
          }
        ]
      },
      isOrderShow: true,//控制点击按钮后样式显示隐藏
      isQuestionShow: true,
      questionType: [],
      questionTypeNum: 0,
      questionNum: 0,
      endTime: '',//动态获取截止时间
      h: -1,//时
      m: -1,//分
      s: -1,//秒
      examPaperCode: '',
      examId: 0,
      singleChoice: [],
      multipleChoice: [],
      judgment: [],
      fillTheBlanks: [],
      shortAnswer: [],
      stem: '',//此时页面题目
      qid: 0,//此时题目的id
      order: 1,//题目序号
      options: [],//选项
      singleChoiceRadio: -1,//单选题选择的选项
      judgmentRadio: -1,//判断题选择的选项
      multipleChoiceRadio: [],//多选题选择的选项
      fillTheBlanksAnswer: '',//填空题答案
      shortAnswerAnswers: '',//简答题答案
      videoWidth: 160,
      videoHeight: 100,
      imgSrc: '',
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
    }
  },
  methods: {
    submitPaper() {
      this.test();
    },
    test() {
      this.setImage();
      let imgSrc = {image: this.imgSrc}
      randImage(imgSrc).then((params) => {
        console.log(params.data);
        if (params.data.code === 0) {
          this.$message({
            message: params.data.msg,
            type: 'success'
          });
        } else if (params.data.code === 1) {
          this.$message({
            message: params.data.msg,
            type: 'warning'
          });
        } else if (params.data.code === 2) {
          this.$message({
            message: params.data.msg,
            type: 'warning'
          });
          setTimeout(randImage(), 2000);
        } else if (params.data.code === 3) {
          this.$message({
            message: params.data.msg,
            type: 'warning'
          });
        } else if (params.data.code === 4) {
          this.$message({
            message: params.data.msg,
            type: 'warning'
          });
        } else if (params.data.code === 5) {
          this.$message.error(params.data.msg);
        }
      });
    },
    changeQuestionType(index) {
      if (this.questionTypeNum !== index) {//点击了这种题型就不能继续点击了
        this.questionTypeNum === index ? this.isOrderShow = !this.isOrderShow : this.isOrderShow = true;
        this.questionTypeNum = index;
        this.questionNum = 0;//切换题型时让题目到1
      }
      //改变题型时，将第一题题目渲染
      this.questionStem(this.questionNum);
    },
    changeQuestionNum(index) {
      if (this.questionNum !== index) {//点击了这道题就不能继续点击了
        this.questionNum === index ? this.isQuestionShow = !this.isQuestionShow : this.isQuestionShow = true;
        this.questionNum = index;//此道题的是哪一个题
      }
      //换题目序号时，将序号题目渲染
      this.questionStem(index);
      this.singleChoiceRadio = -1;
      this.judgmentRadio = -1;
      this.multipleChoiceRadio = [];
      this.fillTheBlanksAnswer = '';
      this.shortAnswerAnswers = '';
    },
    changeSingleOptions() {
      this.result.singleChoice.splice(this.questionNum, 1, {
        qid: this.qid,
        answer: this.singleChoiceRadio
      })
    },
    changeMultiOptions() {
      this.result.multipleChoice.splice(this.questionNum, 1, {
        qid: this.qid,
        answers: this.multipleChoiceRadio
      })
    },
    changeJudgeOptions() {
      this.result.judgment.splice(this.questionNum, 1, {
        qid: this.qid,
        answer: this.judgmentRadio
      })
    },
    preserve() {
      if (this.questionTypeNum === 3) {
        this.result.fillTheBlanks.splice(this.questionNum, 1, {
          qid: this.qid,
          answers: this.fillTheBlanksAnswer
        })
      } else if (this.questionTypeNum === 4) {
        this.result.shortAnswer.splice(this.questionNum, 1, {
          qid: this.qid,
          answers: this.shortAnswerAnswers
        })
      }
    },
    countTime() {
      //获取当前时间
      let date = new Date();
      let now = date.getTime();
      //设置截止时间
      let endTime = new Date(this.endTime);
      let end = endTime.getTime();
      //时间差
      let leftTime = end - now;
      //定义变量 h,m,s保存倒计时的时间
      if (leftTime >= 0) {
        this.h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
        this.m = Math.floor(leftTime / 1000 / 60 % 60);
        this.s = Math.floor(leftTime / 1000 % 60);
      }
      if (this.m === 0 && this.h === 0 && this.s === 0) {//到时间后自动提交
        this.finishPaper();
      }
      //随机抓拍
      let randNum = Math.floor(Math.random() * 600);//0至599的随机数
      if (randNum === 520) {//每一秒有1/600的概略抓拍
        this.test();
      }

      //获取教师监考信息
      returnOriginalState(this.examId).then(res=>{
        if(res.code!==0){
          console.log(res)
          if(res.code===2){
            this.setImage();
            let imgSrc = {image: this.imgSrc}
            addFaceToTeacher(imgSrc);
          }else if(res.code ===1){
            this.$alert(res.msg, '教师提醒你：', {
              confirmButtonText: '确定',
              callback: action => {
                this.$message({
                  type: 'info',
                  message: `action: ${action}`
                });
              }
            });
          }else if(res.code===3){
            this.finishPaper();
          }
        }
      })

      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(this.countTime, 1000);
    },
    getExamPaperCode() {
      // 将数据放在当前组件的数据内
      this.examPaperCode = this.$route.params.examPaperCode;
      this.examId = this.$route.params.examId;
      this.result.examId = this.examId;
      this.result.examPaperCode = this.examPaperCode;
    },
    questionStem(index) {
      if (this.questionTypeNum === 0) {//单选题时
        this.order = this.singleChoice[index].order;
        this.stem = this.singleChoice[index].stem;
        this.qid = this.singleChoice[index].qid;
        for (let i = 0; i < 4; i++) {
          this.options[i] = this.singleChoice[index].options[i].content;
        }
      } else if (this.questionTypeNum === 1) {//多选题
        this.order = this.multipleChoice[index].order;
        this.stem = this.multipleChoice[index].stem;
        this.qid = this.multipleChoice[index].qid;
        for (let i = 0; i < 4; i++) {
          this.options[i] = this.multipleChoice[index].options[i].content;
        }
      } else if (this.questionTypeNum === 2) {//判断题
        this.order = this.judgment[index].order;
        this.stem = this.judgment[index].stem;
        this.qid = this.judgment[index].qid;
      } else if (this.questionTypeNum === 3) {//填空题
        this.order = this.fillTheBlanks[index].order;
        this.stem = this.fillTheBlanks[index].stem;
        this.qid = this.fillTheBlanks[index].qid;
      } else if (this.questionTypeNum === 4) {//简答题
        this.order = this.shortAnswer[index].order;
        this.stem = this.shortAnswer[index].stem;
        this.qid = this.shortAnswer[index].qid;
      }
    },
    backHome() {
      this.$router.replace('/home');
    },
    finishPaper() {
      this.stopNavigator();//关闭摄像头
      endExam(JSON.stringify(this.result)).then((params) => {
        if (params.data.code === 0) {
          this.$message({
            message: '提交成功，即将返回首页',
            type: 'success'
          });
          setTimeout(this.backHome, 2000)
        } else {
          this.$message.error('提交失败');
        }
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(() => {
          done();
        })
        .catch(() => {
        });
    },
    listenVisible(evt, hidden) {
      console.log('隐藏: ' + hidden)
    },

    //调用权限
    getCompetence() {
      let _this = this
      this.thisCancas = document.getElementById('canvasCamera')
      this.thisContext = this.thisCancas.getContext('2d')
      this.thisVideo = document.getElementById('videoCamera')
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加
      // 它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
          })
        }
      }
      let constraints = {
        audio: false,
        video: {width: this.videoWidth, height: this.videoHeight, transform: 'scaleX(-1)'}
      }
      navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
        // 旧的浏览器可能没有srcObject
        if ('srcObject' in _this.thisVideo) {
          _this.thisVideo.srcObject = stream
        } else {
          // 避免在新的浏览器中使用它，因为它正在被弃用。
          _this.thisVideo.src = window.URL.createObjectURL(stream)
        }
        _this.thisVideo.onloadedmetadata = function () {
          _this.thisVideo.play()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    //  绘制图片（拍照功能）
    setImage() {
      let _this = this
      // 点击，canvas画图
      _this.thisContext.drawImage(_this.thisVideo, 0, 0, _this.videoWidth, _this.videoHeight)
      // 获取图片base64链接
      let image = this.thisCancas.toDataURL('image/png')
      _this.imgSrc = image
      this.$emit('refreshDataList', this.imgSrc)
    },
    // 关闭摄像头
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop()
    }
  },
  mounted() {
    this.getCompetence();
    let loading = Loading.service({fullscreen: true});
    this.countTime();//调用定时器
    let testMessage = {examId: this.examId, examPaperCode: this.examPaperCode}
    startExam(JSON.stringify(testMessage)).then((params) => {
      this.stem = params.data.data.singleChoice[0].stem;//加载时先渲染第一题题目
      this.qid = params.data.data.singleChoice[0].qid;//加载时先渲染第一题题目id
      for (let i = 0; i < 4; i++) {//加载时先渲染第一题选项
        this.options[i] = params.data.data.singleChoice[0].options[i].content;
      }
      this.endTime = params.data.data.endTime;
      this.singleChoice = params.data.data.singleChoice;
      this.multipleChoice = params.data.data.multipleChoice;
      this.judgment = params.data.data.judgment;
      this.shortAnswer = params.data.data.shortAnswer;
      this.fillTheBlanks = params.data.data.fillTheBlanks;
      this.questionType = params.data.data.questionTypes;
      loading.close();
    })
    window.addEventListener("visibilitychange", () => {
      if (document.visibilityState === "hidden") {
        this.dialogCount++;
        if (this.dialogCount < 2) {
          this.dialogVisible = true;
        }
        if (this.dialogCount === 100) {//直接提交试卷
          this.finishPaper();
        }
      }
    })
  },
  created() {
    this.getExamPaperCode();
  },
  watch: {
    // 监测路由变化,只要变化了就调用获取路由参数方法将数据存储本组件即可
    '$route': 'getExamPaperCode'
  }

}
</script>

<style lang="less" scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 0;
}

.box-card {
  display: inline-block;
  width: 350px;
}

.paper-message {
  margin-top: 10px;
}

.paper-question-type, .paper-question-num {
  span {
    display: inline-block;
    text-align: center;
    border-style: solid;
    border-width: 1px;
    border-color: #808080;
    color: #808080;
  }

  span:hover {
    background-color: #6dbfff;
  }
}

.paper-question-type {
  span {
    width: 55px;
    height: 30px;
    line-height: 30px;
    border-radius: 10px;
    margin: 10px 8px 0 8px;
  }
}

.paper-question-num {
  span {
    width: 25px;
    height: 25px;
    line-height: 25px;
    border-radius: 3px;
    margin: 8px 8px 0 8px;
  }
}

.checkedType, .checkedNum {
  background-color: #6dbfff;
  border: 0;
}

.paper-submit {
  margin-left: 80px;
}

.paper-order {
  position: absolute;
  top: 12%;
  left: 5%;
  display: inline-block;
  width: 24%;
  height: 80%;
}

.paper-question-content {
  position: absolute;
  top: 12%;
  left: 30%;
  display: inline-block;
  width: 50%;
  height: 68%;
  margin-left: 20px;
  border-style: solid;
  border-width: 1px;
  border-color: #808080;
}

.paper-face {
  position: absolute;
  top: 12%;
  right: 5%;
  display: inline-block;
}

.paper-stem {
  display: block;
  margin-top: 10px;
  font-size: 20px;
  width: 100%;
  height: auto;
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
}

.el-radio, .el-checkbox {
  margin-left: 10px;
  font-size: 40px;
  width: 100%;
  height: auto;
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
}

.paper-fill, .paper-short {
  text-align: center;
  margin-top: 40px;
  margin-left: 10px;
  width: 50%;
}
.paper-short {
  .el-button {
    margin-top: 20px;
  }
}
.t{
  /deep/p {
    display: inline-block;
  }
}
</style>
